/*********************************************************************************
 *      Copyright:  (C) 2024 LingYun<iot25@lingyun>
 *                  All rights reserved.
 *
 *       Filename:  thread.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(11/12/24)
 *         Author:  LingYun <iot25@lingyun>
 *      ChangeLog:  1, Release initial version on "11/12/24 18:15:44"
 *                 
 ********************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#include "thread.h"

//线程池中的线程数组
static pthread_t   *threads = NULL;

//初始化线程池，分配一定数量的线程
int thread_init(int num_threads)
{
	//为线程池分配内存
	threads = (pthread_t *)malloc(sizeof(pthread_t)* num_threads);
	if( threads == NULL )
	{
		printf("malloc failure :%s.\n",strerror(errno));
		return -1;  //分配内存失败，返回-1
	}
	return 0; //初始化成功
}

//创建一个线程
int create_thread(pthread_t *thread, void *(*start_routine)(void *), void *thread_arg) 
{
    return pthread_create(thread, NULL, start_routine, thread_arg);  // 创建并启动线程
}

//启动线程的函数
int thread_start(pthread_t *thread_id, THREAD_BODY *thread_workbody, void *thread_arg)
{
	int					rv = -1;
	pthread_attr_t 		thread_attr;

	//初始化线程属性
	if (pthread_attr_init(&thread_attr)) 
	{
		printf("pthread_attr_init() failure: %s\n", strerror(errno));
        goto CleanUp;
    }

	//设置线程大小
	if(pthread_attr_setstacksize(&thread_attr, 120 * 1024)) 
	{
        printf("pthread_attr_setstacksize() failure: %s\n", strerror(errno));
        goto CleanUp;
    }

    // 设置线程为分离状态
    if (pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED)) 
	{
        printf("pthread_attr_setdetachstate() failure: %s\n", strerror(errno));
        goto CleanUp;
    }

    // 创建线程
    if (pthread_create(thread_id, &thread_attr, thread_workbody, thread_arg)) 
	{
        printf("Create thread failure: %s\n", strerror(errno));
        goto CleanUp;
    }

    rv = 0;

CleanUp:
    // 销毁线程属性
    pthread_attr_destroy(&thread_attr);
    return rv;
}

//等待所有线程结束
void wait_for_threads(pthread_t *threads, int num_threads) 
{
    for (int i = 0; i < num_threads; i++) 
	{
        pthread_join(threads[i], NULL);  // 等待每个线程结束
    }
}

//销毁线程池，释放资源
void thread_pool_cleanup(pthread_t *threads, int num_threads) 
{
    free(threads);  // 释放线程池内存
}
